package studentdemo.dao;

import studentdemo.modul.Major;
import studentdemo.util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MajorDaoImpl implements MajorDao {
    @Override
    public int insertMajor(Major major) {
        String sql = "INSERT INTO Dujx_Major11 (djx_Mno11, djx_Mname11) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, major.getMno());
            ps.setString(2, major.getMname());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int updateMajor(Major major) {
        String sql = "UPDATE Dujx_Major11 SET djx_Mname11=? WHERE djx_Mno11=?";
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, major.getMname());
            ps.setString(2, major.getMno());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteMajor(String mno) {
        String sql = "DELETE FROM Dujx_Major11 WHERE djx_Mno11=?";
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, mno);
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Major getMajorById(String mno) {
        String sql = "SELECT * FROM Dujx_Major11 WHERE djx_Mno11=?";
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, mno);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Major(rs.getString("djx_Mno11"), rs.getString("djx_Mname11"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Major> getAllMajors() {
        String sql = "SELECT * FROM Dujx_Major11 ORDER BY djx_Mno11";
        List<Major> list = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection(); Statement st = conn.createStatement()) {
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()) {
                list.add(new Major(rs.getString("djx_Mno11"), rs.getString("djx_Mname11")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
} 